//
//  JHOAuthViewController.swift
//  Weibo_SwiftDemo
//
//  Created by gjh on 2021/1/3.
//

import UIKit
//import WebKit
import SVProgressHUD

// 通过webView 加载微博授权页面
class JHOAuthViewController: UIViewController {

    // 懒加载
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        view.backgroundColor = Spec.color.white
        // 取消滚动视图
        webView.scrollView.isScrollEnabled = false
        
        // 设置代理
        webView.delegate = self
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", titleColor: Spec.color.darkGray, highlightColor: Spec.color.orange, target: self, action: #selector(back), isback: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", titleColor: Spec.color.darkGray, highlightColor: Spec.color.orange, target: self, action: #selector(autoFill))
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(JHClientID)&redirect_uri=\(JHRedirectURI)"
        // 确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        // 建立请求
        let request = URLRequest(url: url)
        // 加载请求
        webView.loadRequest(request)
        
    }
    // MARK: - 监听按钮方法
    @objc private func back() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    // 自动填充, webView 的注入,直接通过 js 修改本地浏览器中缓存的页面内容
    // FIXME: 这个地方有问题,不能自动填充
    @objc private func autoFill() {
        // 准备 JS
        let js = "document.getElementById('username').value = 'gjh52617@126.com';" +
            "document.getElementById('password').value = 'gjh295997340';"
        
        // 执行 JS ,完成回调参数可以不传
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
}
// MARK: - WKNavigationDelegate
extension JHOAuthViewController: UIWebViewDelegate {
    
    /// webview 将要加载请求
    /// - Parameters:
    ///   - webView: webview
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        // 确认思路
        // 1.如果请求地址包含 http://baidu.com 就不加载页面/否则加载页面
        if request.url?.absoluteString.hasPrefix(JHRedirectURI) == false {
            return true
        }
        
        print("加载请求 --- \(request.url?.absoluteString ?? "123")")
        // 从回调地址中查询字符串"code=",如果有授权成功,没有就授权失败
        print("加载请求 --- \(String(describing: request.url?.query))")
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            back()
            return false
        }
        // 3.从 quary 中取出授权码,代码走到此处,url 中一定有查询字符串,并且包含"code="
        guard let code = request.url?.query?.substring(from: "code=".endIndex) else { return false }
        
        print("获取授权码...\(code)")
        // 4.使用授权码去获取 AccessToken
        JHNetworkManager.instance.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                SVProgressHUD.showSuccess(withStatus: "登录成功")
                
                // 下一步做什么,跳转"界面",   通过通知发送登录成功消息
                // 1.发送通知 - 不关心有没有监听者
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: JHUserLoginSuccessedNotification), object: nil)
                // 2.关闭窗口
                self.back()
            }
        }
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
